#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
. "$(dirname -- "$0")/log.sh"
# . "$(dirname -- "$0")/valid-checkout.sh"

# 获取项目名称
projectName=""
# 项目id
projectId=""
# 定义是否为特性分支
isSpecial=false

getProjectName(){
  packageJsonPath="$(pwd)/package.json"
  projectName=$(grep -o '"projectName": *"[^"]*"' "$packageJsonPath" | cut -d '"' -f 4)
  projectId=$(grep -o '"projectId": *"[^"]*"' "$packageJsonPath" | cut -d '"' -f 4)
  packageJsonName=$(grep -o '"name": *"[^"]*"' "$packageJsonPath" | cut -d '"' -f 4)

  if [[ !projectName ]]; then
    projectName=$packageJsonName
  fi
}
getProjectName

isSpecialBranch() {
  array=("master" "pre" "test" "develop")
  if [[ "${array[@]}" =~ "${1}" ]]; then
     isSpecial=true
  else
      isSpecial=false
  fi
}

# 发送钉钉消息
function sendDingtalk() {
  jsonData="{\"systemId\": $projectId }"
  respone=$(curl  -s -X POST -H 'Content-Type: application/json' -d "${jsonData}"  https://lowcoding.kapeixi.cn/v1/githook-config/index )
  if [[ $? -eq 0 ]]; then
     ROBOTS=($(echo $respone | grep -o '"pushUrl": *"[^"]*"' | sed 's/"pushUrl": *"\([^"]*\)"/\1/'))
  fi
  if [[ ${#ROBOTS[@]} == 0 ]]; then
    ROBOTS=('https://oapi.dingtalk.com/robot/send?access_token=b100d5db1d3e9cb932c61dc96c5a6788eda55bb390d4d2e739ea734fc31249e7')
  fi
  
  # # 调用你的API
  for item in "${ROBOTS[@]}"; do
      curl -X POST -H 'Content-Type: application/json' -d "$1"  $item
  done
}


# 获取用户名
userName=$(git config user.name)


# 获取远程分支的引用
while read local_ref local_sha remote_ref remote_sha
do
  # 定义允许的分支名正则表达式
  allowed_branch_regex="^([A-Z]{0,4}-|[\s\S]{0})(feature|bugfix|hotfix|release)/[a-zA-Z0-9_-]+$"

  # 获取分支的名字

  # echo $(git rev-parse --abbrev-ref HEAD)
  # branch_name=$(basename "$local_ref")

  branch_name=$(git rev-parse --abbrev-ref HEAD)

   # 检查是否包含删除操作
 if [[ "${local_sha}" == "0000000000000000000000000000000000000000" ]]; then

     deleted_branch=$(echo "${remote_ref}" | sed 's|refs/heads/||')

     if [[ $deleted_branch == 'test' || $deleted_branch == 'pre' ]]; then
       json_data='{"msgtype":"text","at":{"isAtAll":true},"text":{"content":' 
        json_data+="\"【${userName}】删除了${projectName}项目的分支【${deleted_branch}】\""
        json_data+='}}'
          # # 调用你的API
        sendDingtalk $json_data

        exit 0
      elif [[ $deleted_branch == 'master' ]]; then  
          error "生产环境master分支不允许删除"
        json_data='{"msgtype":"text","at":{"isAtAll":true},"text":{"content":' 
        json_data+="\"【${userName}】执行了删除${projectName}项目的分支【${deleted_branch}】\""
        json_data+='}}'
        sendDingtalk $json_data
        exit 1
      fi
    
   else
      # 判断是否为特性分支
      
     isSpecialBranch $branch_name

    # 检查分支名是否符合规定
      if ! [[ "$branch_name" =~ $allowed_branch_regex  || $isSpecial = true ]]; then
        error "Invalid branch name '$branch_name'."
        info "Branch names must match the pattern: $allowed_branch_regex"
        exit 1
      fi
    
  fi
done

# 允许推送
exit 0
